package cn.wowjoy.office.materialinspection.xunjian.detail;

import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.load.model.GlideUrl;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.adapter.DeviceDetailPhotoAdapter;
import cn.wowjoy.office.common.adapter.MLinearLayoutManager;
import cn.wowjoy.office.common.widget.AlphaManager;
import cn.wowjoy.office.common.widget.BottomMenuPopup;
import cn.wowjoy.office.common.widget.BottomMenuPopupN;
import cn.wowjoy.office.common.widget.CheckImgvPop;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.common.widget.PhotoPreviewDialog;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.request.InspectRecordControllerRequest;
import cn.wowjoy.office.data.response.InspectRecordControllerResponse;
import cn.wowjoy.office.data.response.InspectTaskDtlVO;
import cn.wowjoy.office.data.response.InspectTaskSelect;
import cn.wowjoy.office.data.response.SingleTaskController;
import cn.wowjoy.office.databinding.ActivityDeviceDetailBinding;
import cn.wowjoy.office.utils.ImageSelectorUtils;
import cn.wowjoy.office.utils.MD5Util;
import cn.wowjoy.office.utils.PreferenceManager;
import cn.wowjoy.office.utils.ToastUtil;

public class DeviceDetailActivity extends NewBaseActivity<ActivityDeviceDetailBinding, DeviceDetailViewModel> implements View.OnClickListener {
    private static final int REQUEST_CODE = 0x00000011;

    String key = "";
    boolean isDone;
    public InspectTaskDtlVO inspectTaskDtlVO;
    SingleTaskController single;
    boolean isShow;  //  是扫码进入的详情页  还是 手点进来的

    boolean isLocal = false; // 是本地图片 还是网络图片
    boolean isDelete = false; // 是否是删除图片

    private BottomMenuPopup mMenuPop1;
    private BottomMenuPopupN mMenuPop2;
    private CheckImgvPop checkImgvPop;
    // 单图片路径
    public String filePath;
    InspectRecordControllerRequest request;
    private ArrayList<String> imagePaths;
    private boolean isSecond = false; // 是否第二次编辑
    private boolean isEdit = false;

    private boolean isFind; //是否找到广播对应
    private List<String> mStrings;

    public String taskDtlId;
    public String totalId;

    public String qrCode;
    private MDialog mDialog;//提交
    private MDialog mFail;
    private PhotoPreviewDialog mPhotoPreviewDialog;

    

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setViewModel(viewModel);
        initListener();
        initRVAdapter();//初始化Adapter
        initSelector(); //初始化 动作条选择
        initObserve();
    }
    private MDialog waitDialog;
    private void initObserve() {
        viewModel.getSubmit().observe(this, new Observer<LiveDataWrapper<InspectRecordControllerResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<InspectRecordControllerResponse> inspectionTaskControllerResponseLiveDataWrapper) {
                switch (inspectionTaskControllerResponseLiveDataWrapper.status){
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(DeviceDetailActivity.this);
                        break;
                    case SUCCESS:
                        if(null != waitDialog){
                            CreateDialog.dismiss(DeviceDetailActivity.this, waitDialog);
                        }
                       setResult(Constants.RESULT_OK);
                       finish();
                        break;
                    case ERROR:
                        if(null != waitDialog){
                            CreateDialog.dismiss(DeviceDetailActivity.this, waitDialog);
                        }
                        handleException(inspectionTaskControllerResponseLiveDataWrapper.error,false);
                        break;
                }
            }
        });
        viewModel.getSubmitByBroadcast().observe(this, new Observer<LiveDataWrapper<InspectRecordControllerResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<InspectRecordControllerResponse> inspectionTaskControllerResponseLiveDataWrapper) {
                switch (inspectionTaskControllerResponseLiveDataWrapper.status){
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(DeviceDetailActivity.this);
                        break;
                    case SUCCESS:
                        if(null != waitDialog){
                            CreateDialog.dismiss(DeviceDetailActivity.this, waitDialog);
                        }
                        qrCode = key;
                        isDone = false;
                        isShow = false;
                        taskDtlId = null;
                        if(null != qrCode && !"".equals(qrCode)){
                            if( !isUUID(qrCode)){
                                return;
                            }
                        }
                        viewModel.selectDtl(DeviceDetailActivity.this.totalId,null,qrCode);
                        break;
                    case ERROR:
                        if(null != waitDialog){
                            CreateDialog.dismiss(DeviceDetailActivity.this, waitDialog);
                        }
                        handleException(inspectionTaskControllerResponseLiveDataWrapper.error,false);
                        break;
                }
            }
        });
        viewModel.getSelectDtl().observe(this, new Observer<LiveDataWrapper<InspectTaskSelect>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<InspectTaskSelect> inspectionTaskControllerResponseLiveDataWrapper) {
                switch (inspectionTaskControllerResponseLiveDataWrapper.status) {
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(DeviceDetailActivity.this);
                        break;
                    case SUCCESS:
                        if (null != waitDialog) {
                            CreateDialog.dismiss(DeviceDetailActivity.this, waitDialog);
                        }
                        if (null != inspectionTaskControllerResponseLiveDataWrapper.data && null != inspectionTaskControllerResponseLiveDataWrapper.data.getSingle()) {
                            InspectTaskSelect total = inspectionTaskControllerResponseLiveDataWrapper.data;
                            inspectTaskDtlVO = total.getSingle();
                            if (null != total.getMsg() && "当前资产不在巡检范围内".equals(total.getMsg())) {
                                commonUI(total.getSingle(), false);
                                return;
                            }
                            if (!isLocal) {
                                showUI(total.getSingle());
                            }
                        }
                            break;
                            case ERROR:
                                if (null != waitDialog) {
                                    CreateDialog.dismiss(DeviceDetailActivity.this, waitDialog);
                                }
                                handleException(inspectionTaskControllerResponseLiveDataWrapper.error, true);
                                 finish();
                                break;
                        }
                }
        });
    }

    private void initListener() {
        binding.deviceTitle.titleTextTv.setText("设备巡检详情");
        binding.deviceTitle.titleBackLl.setVisibility(View.VISIBLE);
        binding.deviceTitle.titleBackTv.setText("");
        binding.deviceTitle.titleBackLl.setOnClickListener(this);
//        binding.materialTitle.titleMenuConfirm.setVisibility(View.VISIBLE);
        binding.deviceTitle.titleMenuConfirm.setText("保存");
        binding.deviceTitle.titleMenuConfirm.setOnClickListener(this);
        binding.waiguan.setText(Html.fromHtml(getString(R.string.divice_notice2)));
        binding.shebeizhuangkuang.setText(Html.fromHtml(getString(R.string.divice_notice)));
    }

    private void initSelector() {
        binding.rlOutlookAddedNodone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //实例化SelectPicPopupWindow
                isEdit = true;
                if (null == mMenuPop1) {
                    mMenuPop1 = new BottomMenuPopup(DeviceDetailActivity.this, itemsOnClick_OutAdded, binding.tvOutlookAddedStateDevicedetail.getText().toString());
                    mMenuPop1.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            AlphaManager.backgroundAlpha(1f, DeviceDetailActivity.this);
                        }
                    });
                }
                //显示窗口
                mMenuPop1.showAtLocation(DeviceDetailActivity.this.findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                AlphaManager.backgroundAlpha(0.7f, DeviceDetailActivity.this);
            }
        });
        binding.rlDeviceStateNodone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isEdit = true;
                //实例化SelectPicPopupWindow
                if (null == mMenuPop2) {
                    mMenuPop2 = new BottomMenuPopupN(DeviceDetailActivity.this, itemsOnClick_device, isShow, binding.tvDeviceStateDevicedetail.getText().toString().trim());
                    mMenuPop2.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            AlphaManager.backgroundAlpha(1f, DeviceDetailActivity.this);
                        }
                    });
                }
                //显示窗口
                mMenuPop2.showAtLocation(DeviceDetailActivity.this.findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                AlphaManager.backgroundAlpha(0.7f, DeviceDetailActivity.this);
            }
        });
        // 添加照片
        binding.imgvAddPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageSelectorUtils.openPhoto(DeviceDetailActivity.this, REQUEST_CODE, true, 1);
            }
        });
        //点击查看调出大图
        binding.tvLookDevicedetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != inspectTaskDtlVO && null != inspectTaskDtlVO.getAssetsPictureIdUrl()) {
                    GlideUrl glideUrlHeaderUrl = viewModel.getGlideUrlHeaderUrl(inspectTaskDtlVO.getAssetsPictureIdUrl(), PreferenceManager.getInstance().getHeaderToken());
                    checkImgvPop = new CheckImgvPop(DeviceDetailActivity.this, glideUrlHeaderUrl);
                    checkImgvPop.showAsDropDown(binding.rlLook);
                    AlphaManager.backgroundAlpha(0.7f, DeviceDetailActivity.this);
                }
            }
        });
        // TODO:字数限制
        binding.remark.addTextChangedListener(new MyTextWatcher(binding.remark, 25, DeviceDetailActivity.this));
        binding.remark.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (!v.getText().toString().equals(binding.remark.getText().toString())) {
                            isEdit = true;
                        }
                        return true;
            }
        });
    }

    private void initRVAdapter() {
        MLinearLayoutManager mLinearLayoutManager = new MLinearLayoutManager(this);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mLinearLayoutManager.setScrollEnabled(false);
        MLinearLayoutManager mLinearLayoutManager2 = new MLinearLayoutManager(this);
        mLinearLayoutManager2.setOrientation(LinearLayoutManager.HORIZONTAL);
        mLinearLayoutManager2.setScrollEnabled(false);
        binding.rvPhotos.setLayoutManager(mLinearLayoutManager);
        binding.rvPhotos.setAdapter(viewModel.mDeviceDetailPhotoAdapter);
        binding.rvPhotosDone.setLayoutManager(mLinearLayoutManager2);
        viewModel.mDeviceDetailPhotoDoneAdapter.setDeleteGone(true); //不叉叉
        binding.rvPhotosDone.setAdapter(viewModel.mDeviceDetailPhotoDoneAdapter);
        viewModel.mDeviceDetailPhotoAdapter.setOnclickItemListener(new DeviceDetailPhotoAdapter.OnclickItemListener() {
            @Override
            public void delete() {
                if (null != imagePaths && imagePaths.size() > 0) {
                    imagePaths.clear(); //清楚所有图片地址
                    imagePaths = null;
                }
                isDelete = true;
                isEdit = true;
            }

            @Override
            public void enlarge(String url) {
                if (null != url && !"".equals(url)) {
                    if (null == mStrings) {
                        mStrings = new ArrayList<>();
                    }
                    mStrings.clear();
                    mStrings.add(url);
                    mPhotoPreviewDialog = new PhotoPreviewDialog.Builder()
                            .needHeader(PreferenceManager.getInstance().getHeaderToken())
                            .index(0)
                            .path(mStrings)
                            .build();
                    mPhotoPreviewDialog.show(getSupportFragmentManager(), null);
                }
            }
        });
        viewModel.mDeviceDetailPhotoDoneAdapter.setOnclickItemListener(new DeviceDetailPhotoAdapter.OnclickItemListener() {
            @Override
            public void delete() {
            }

            @Override
            public void enlarge(String url) {
                if (null != url && !"".equals(url)) {
                    if (null == mStrings) {
                        mStrings = new ArrayList<>();
                    }
                    mStrings.clear();
                    mStrings.add(url);
                    mPhotoPreviewDialog = new PhotoPreviewDialog.Builder()
                            .needHeader(PreferenceManager.getInstance().getHeaderToken())
                            .index(0)
                            .path(mStrings)
                            .build();
                    mPhotoPreviewDialog.show(getSupportFragmentManager(), null);
            }
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && data != null) {
            ArrayList<String> images = data.getStringArrayListExtra(ImageSelectorUtils.SELECT_RESULT);
            filePath = images.get(0);
            isLocal = true;
            isDelete = false;
            isEdit = true;
            //每次获取本地图片后进行压缩，因为压缩需要时间约1s,异步返回，保证一般情况下可以在保存操作之前压缩完成
            Tiny.FileCompressOptions options = new Tiny.FileCompressOptions();
            if (null == imagePaths) {
                imagePaths = new ArrayList<>();
            }
            imagePaths.clear();
            imagePaths.add(filePath);

            Tiny.getInstance().source(filePath).asFile().withOptions(options).compress(new FileCallback() {
                @Override
                public void callback(boolean isSuccess, String outfile) {
                    if (isSuccess) {
                        imagePaths.add(outfile);
                    }
                }
            });
            binding.rvPhotos.setVisibility(View.VISIBLE);
            viewModel.mDeviceDetailPhotoAdapter.setBitmaps(filePath);
        }

    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick_OutAdded = new View.OnClickListener() {

        public void onClick(View v) {
            if (null != mMenuPop1 && mMenuPop1.isShowing()) {
                mMenuPop1.dismiss();
            }
            switch (v.getId()) {
                case R.id.rl_normal:
                    binding.tvOutlookAddedStateDevicedetail.setText("正常");
                    mMenuPop1.setRight("正常");
                    AlphaManager.backgroundAlpha(1.0f, DeviceDetailActivity.this);
                    if ("正常".equals(binding.tvDeviceStateDevicedetail.getText().toString().trim())
                            || "不存在".equals(binding.tvDeviceStateDevicedetail.getText().toString().trim())) {
                        binding.beizhu.setText("备注");
                    }
                    break;
                case R.id.rl_error:
                    binding.tvOutlookAddedStateDevicedetail.setText("异常");
                    mMenuPop1.setRight("异常");
                    AlphaManager.backgroundAlpha(1.0f, DeviceDetailActivity.this);
//                    binding.beizhu.setText("* 备注");
                    setRemark();
                    break;
                default:
                    break;
            }
        }
    };
    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick_device = new View.OnClickListener() {

        public void onClick(View v) {
            if (null != mMenuPop2 && mMenuPop2.isShowing()) {
                mMenuPop2.dismiss();
            }
            switch (v.getId()) {
                case R.id.rl_normal:
                    binding.tvDeviceStateDevicedetail.setText("正常");
                    mMenuPop2.setRight("正常");
                    AlphaManager.backgroundAlpha(1.0f, DeviceDetailActivity.this);
                    if ("正常".equals(binding.tvOutlookAddedStateDevicedetail.getText().toString().trim())) {
                        binding.beizhu.setText("备注");
                    }
                    break;
                case R.id.rl_error:
                    binding.tvDeviceStateDevicedetail.setText("异常");
                    mMenuPop2.setRight("异常");
                    AlphaManager.backgroundAlpha(1.0f, DeviceDetailActivity.this);

                    //有异常 必须填写备注
//                    binding.beizhu.setText("* 备注");
                    setRemark();
                    break;
                case R.id.rl_no_exist:
                    binding.tvDeviceStateDevicedetail.setText("不存在");
                    mMenuPop2.setRight("不存在");
                    AlphaManager.backgroundAlpha(1.0f, DeviceDetailActivity.this);

                    //有异常 必须填写备注
//                    binding.beizhu.setText("* 备注");
                    setRemark();
                    break;
                default:
                    break;
            }
        }
    };

    private void setRemark() {
        binding.beizhu.setText(Html.fromHtml(getString(R.string.divice_notice3)));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_device_detail;
    }

    @Override
    public void onBackPressed() {
        if (isEdit) {
            mDialog = CreateDialog.infoDialog(DeviceDetailActivity.this, "提醒", "该巡检详情还未保存，是否退出", "否", "是", v12 -> {
                if (null != mDialog) {
                    mDialog.cancel();
                }
            }, v1 -> {
                if (null != mDialog) {
                    mDialog.cancel();
                    setResult(Constants.RESULT_OK);
                    finish();
                }
            });
        } else {
            setResult(Constants.RESULT_OK);
            finish();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(!isDone){
            closeBroadCast();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        isFind = getIntent().getExtras().getBoolean("isFind");
        isDone = getIntent().getExtras().getBoolean("isDone");
        taskDtlId = getIntent().getExtras().getString("taskDtlId");
        isShow = getIntent().getExtras().getBoolean("isShow");
//        if (isShow) {
//            totalId = getIntent().getExtras().getString("totalId"); // z注意扫码进来是没有这个值的，且提交的时候不需要
//        } else {
//            //扫码进来的
//            qrCode = getIntent().getExtras().getString("qrCode");
//        }
        totalId = getIntent().getExtras().getString("totalId"); // z注意扫码进来是没有这个值的，且提交的时候不需要
        qrCode = getIntent().getExtras().getString("qrCode");
        if(!isDone){
            openBroadCast();
        }
        //判断 是否符合UUID的规则
        if(null != qrCode && !"".equals(qrCode)){
            if( !isUUID(qrCode)){
                return;
            }
        }
        viewModel.selectDtl(totalId,taskDtlId, qrCode);
    }

    public boolean isUUID(String qrCode) {
        if(null != qrCode && !"".equals(qrCode) ){
            if(!MD5Util.IsUUID(qrCode)){
                binding.main.setVisibility(View.GONE);
                binding.imgvUnknown.setVisibility(View.VISIBLE);
                binding.tvUnknown.setVisibility(View.VISIBLE);
                binding.deviceTitle.titleMenuConfirm.setVisibility(View.GONE);
                binding.deviceTitle.titleTextTv.setText("错误");
                isFind = false;
                return false;
            }
        }
        return true;
    }

    public void commonUI(InspectTaskDtlVO inspectTaskDtlVO, boolean isFind) {
        this.isFind = isFind;
        binding.main.setVisibility(View.VISIBLE);
        binding.imgvUnknown.setVisibility(View.GONE);
        binding.tvUnknown.setVisibility(View.GONE);
        if (!isFind) {
            binding.rlNotFind.setVisibility(View.VISIBLE);
            binding.rlOutlookAddedNodone.setVisibility(View.GONE);
            binding.rlDeviceStateNodone.setVisibility(View.GONE);
            binding.rlRemarkNodone.setVisibility(View.GONE);
            binding.deviceTitle.titleTextTv.setText("错误");
            binding.deviceTitle.titleMenuConfirm.setVisibility(View.GONE);
        } else {
            binding.rlNotFind.setVisibility(View.GONE);
            binding.rlOutlookAddedNodone.setVisibility(View.VISIBLE);
            binding.rlDeviceStateNodone.setVisibility(View.VISIBLE);
            binding.rlRemarkNodone.setVisibility(View.VISIBLE);
            binding.deviceTitle.titleTextTv.setText("设备巡检详情");
            binding.deviceTitle.titleMenuConfirm.setVisibility(View.VISIBLE);
        }
        if (null != inspectTaskDtlVO) {
            if (null != inspectTaskDtlVO.getCardNo()) {   //资产编码
                binding.tvCardNo.setText(inspectTaskDtlVO.getCardNo());
            }
            if (null != inspectTaskDtlVO.getCardName()) {  //资产名称
                binding.tvDeviceNameDevicedetail.setText(inspectTaskDtlVO.getCardName());
            }
            if (null != inspectTaskDtlVO.getProduceNo()) {  //出场设备
                binding.tvProduceNo.setText(inspectTaskDtlVO.getProduceNo());
            }
            if (null != inspectTaskDtlVO.getInspectRecordDtlId()) {
                isSecond = true;
            }
        }

        // 查看按钮是否显示
        if (null != inspectTaskDtlVO && null != inspectTaskDtlVO.getAssetsPictureIdUrl() && !"".equals(inspectTaskDtlVO.getAssetsPictureIdUrl())) {
            binding.tvLookDevicedetail.setVisibility(View.VISIBLE);
        } else {
            binding.tvLookDevicedetail.setVisibility(View.GONE);
        }
    }

    public void showUI(InspectTaskDtlVO inspectTaskDtlVO) {

        commonUI(inspectTaskDtlVO, true);
        if (isDone) {
            //已完成的界面
            binding.rlDeviceStateNodone.setVisibility(View.GONE);
            binding.rlDeviceStateDone.setVisibility(View.VISIBLE);

            binding.rlOutlookAddedNodone.setVisibility(View.GONE);
            binding.rlOutlookAddedDone.setVisibility(View.VISIBLE);

            binding.rlRemarkNodone.setVisibility(View.GONE);
            binding.rlRemarkDone.setVisibility(View.VISIBLE);
            binding.deviceTitle.titleMenuConfirm.setVisibility(View.GONE);

            if (null != inspectTaskDtlVO) {
                // 外观
                if (null != inspectTaskDtlVO.getAppearanceStatus() && !"".equals(inspectTaskDtlVO.getAppearanceStatus())) {
                    if ("n".equals(inspectTaskDtlVO.getAppearanceStatus())) {
                        binding.tvOutlookAddedStateDevicedetailDone.setText("异常");
                    } else if ("y".equals(inspectTaskDtlVO.getAppearanceStatus())) {
                        binding.tvOutlookAddedStateDevicedetailDone.setText("正常");
                    }
                }
                // 设备状况
                if (null != inspectTaskDtlVO.getIsExist() && !"".equals(inspectTaskDtlVO.getIsExist())) {
                    if ("n".equals(inspectTaskDtlVO.getIsExist())) {
                        binding.tvDeviceStateDevicedetailDone.setText("不存在");
                    } else if ("y".equals(inspectTaskDtlVO.getIsExist())) {
                        if (null != inspectTaskDtlVO.getAssetsStatus() && !"".equals(inspectTaskDtlVO.getAssetsStatus())) {
                            if ("n".equals(inspectTaskDtlVO.getAssetsStatus())) {
                                binding.tvDeviceStateDevicedetailDone.setText("异常");
                            } else if ("y".equals(inspectTaskDtlVO.getAssetsStatus())) {
                                binding.tvDeviceStateDevicedetailDone.setText("正常");
                            }
                        }
                    }
                }
                //备注
                if (null != inspectTaskDtlVO.getRemarks()) {
                    binding.remarkDone.setText(inspectTaskDtlVO.getRemarks().trim());
                } else {
                    binding.remarkDone.setText("无");
                }
                //巡检时间
                if (null != inspectTaskDtlVO.getInspectDatetime()) {
                    binding.checkTimeDone.setText(inspectTaskDtlVO.getInspectDatetime());
                } else {
                    binding.checkTimeDone.setText("未知");
                }
                //TODO:有图片的状态
                if (null == inspectTaskDtlVO.getThumbnailIdUrl() || "".equals(inspectTaskDtlVO.getThumbnailIdUrl())) {
                    binding.rvPhotosDone.setVisibility(View.GONE);
                }
                if (null == inspectTaskDtlVO.getPictureIdUrl() || "".equals(inspectTaskDtlVO.getPictureIdUrl())) {
                    binding.rvPhotosDone.setVisibility(View.GONE);
                } else {
                    viewModel.mDeviceDetailPhotoDoneAdapter.setBitmaps(inspectTaskDtlVO.getThumbnailIdUrl());
                }
            }

        } else {
            //未完成的界面
            binding.rlDeviceStateNodone.setVisibility(View.VISIBLE);
            binding.rlDeviceStateDone.setVisibility(View.GONE);

            binding.rlOutlookAddedNodone.setVisibility(View.VISIBLE);
            binding.rlOutlookAddedDone.setVisibility(View.GONE);

            binding.rlRemarkNodone.setVisibility(View.VISIBLE);
            binding.rlRemarkDone.setVisibility(View.GONE);

            binding.deviceTitle.titleMenuConfirm.setVisibility(View.VISIBLE);
            //设置状态 1.已经设置过状态 2.未设置过状态
            if (null != inspectTaskDtlVO) {
                // 外观
                if (null != inspectTaskDtlVO.getAppearanceStatus() && !"".equals(inspectTaskDtlVO.getAppearanceStatus())) {
                    if ("n".equals(inspectTaskDtlVO.getAppearanceStatus())) {
                        binding.tvOutlookAddedStateDevicedetail.setText("异常");
                    } else if ("y".equals(inspectTaskDtlVO.getAppearanceStatus())) {
                        binding.tvOutlookAddedStateDevicedetail.setText("正常");
                    }
                }
                // 设备状况
                if (null != inspectTaskDtlVO.getIsExist() && !"".equals(inspectTaskDtlVO.getIsExist())) {
                    if ("n".equals(inspectTaskDtlVO.getIsExist())) {
                        binding.tvDeviceStateDevicedetail.setText("不存在");
                    } else if ("y".equals(inspectTaskDtlVO.getIsExist())) {
                        if (null != inspectTaskDtlVO.getAssetsStatus() && !"".equals(inspectTaskDtlVO.getAssetsStatus())) {
                            if ("n".equals(inspectTaskDtlVO.getAssetsStatus())) {
                                binding.tvDeviceStateDevicedetail.setText("异常");
                            } else if ("y".equals(inspectTaskDtlVO.getAssetsStatus())) {
                                binding.tvDeviceStateDevicedetail.setText("正常");
                            }
                        }
                    }
                }
                // 备注
                if (null != inspectTaskDtlVO.getRemarks()) {
                    binding.remark.setText(inspectTaskDtlVO.getRemarks().trim());
                    binding.remark.setSelection(binding.remark.getText().length());
                } else{
                    binding.remark.setText("");
                }

                // 设置缩略图
                if (!isLocal) {
                    if (null == inspectTaskDtlVO.getThumbnailIdUrl() || "".equals(inspectTaskDtlVO.getThumbnailIdUrl())) {
                        binding.rvPhotosDone.setVisibility(View.GONE);
                    }
                    if (null == inspectTaskDtlVO.getPictureIdUrl() || "".equals(inspectTaskDtlVO.getPictureIdUrl())) {
                        binding.rvPhotos.setVisibility(View.GONE);
                    }
                    if (null != inspectTaskDtlVO.getThumbnailIdUrl()) {
                        viewModel.mDeviceDetailPhotoAdapter.setBitmaps(inspectTaskDtlVO.getThumbnailIdUrl());
                    } else if (null != inspectTaskDtlVO.getPictureIdUrl()) {
                        viewModel.mDeviceDetailPhotoAdapter.setBitmaps(inspectTaskDtlVO.getPictureIdUrl());
                    }
                }

                if (null != inspectTaskDtlVO.getAppearanceStatus() && !"".equals(inspectTaskDtlVO.getAppearanceStatus())) {
                    if ("n".equals(inspectTaskDtlVO.getAppearanceStatus())) {
//                        binding.beizhu.setText("* 备注");
                        setRemark();
                    }
                }
                // 设备状况
                if (null != inspectTaskDtlVO.getIsExist() && !"".equals(inspectTaskDtlVO.getIsExist())) {
                    if ("n".equals(inspectTaskDtlVO.getIsExist())) {
//                        binding.beizhu.setText("* 备注");
                        setRemark();
                        binding.tvDeviceStateDevicedetail.setText("不存在");
                    } else if ("y".equals(inspectTaskDtlVO.getIsExist())) {
                        if (null != inspectTaskDtlVO.getAssetsStatus() && !"".equals(inspectTaskDtlVO.getAssetsStatus())) {
                            if ("n".equals(inspectTaskDtlVO.getAssetsStatus())) {
//                                binding.beizhu.setText("* 备注");
                                setRemark();
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    protected Class<DeviceDetailViewModel> getViewModel() {
        return DeviceDetailViewModel.class;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back_ll:
                if (isEdit) {
                    mDialog = CreateDialog.infoDialog(DeviceDetailActivity.this, "提醒", "该巡检详情还未保存，是否退出", "否", "是", v12 -> {
                        if (null != mDialog) {
                            mDialog.cancel();
                        }
                    }, v1 -> {
                        if (null != mDialog) {
                            mDialog.cancel();
                            setResult(Constants.RESULT_OK);
                            finish();
                        }
                    });
                } else {
                    setResult(Constants.RESULT_OK);
                    finish();
                }
                break;
            case R.id.title_menu_confirm:
                // 外观
                if (null != inspectTaskDtlVO) {
                    if (null != inspectTaskDtlVO.getAppearanceStatus() && !"".equals(inspectTaskDtlVO.getAppearanceStatus())) {
                        if ("n".equals(inspectTaskDtlVO.getAppearanceStatus())) {
//                            binding.beizhu.setText("* 备注");
                            setRemark();
                        }
                    }
                    if (null != inspectTaskDtlVO.getIsExist() && !"".equals(inspectTaskDtlVO.getIsExist())) {
                        if ("n".equals(inspectTaskDtlVO.getIsExist())) {
//                            binding.beizhu.setText("* 备注");
                            setRemark();
                        } else if ("y".equals(inspectTaskDtlVO.getIsExist())) {
                            if (null != inspectTaskDtlVO.getAssetsStatus() && !"".equals(inspectTaskDtlVO.getAssetsStatus())) {
                                if ("n".equals(inspectTaskDtlVO.getAssetsStatus())) {
//                                    binding.beizhu.setText("* 备注");
                                    setRemark();
                                }
                            }
                        }
                    }
                }
                if (binding.beizhu.getText().toString().contains("*") && 0 == binding.remark.getText().length()) {
                    ToastUtil.toastWarning(DeviceDetailActivity.this, "请添加备注说明", -1);
                    return;
                }
                submit();
                // 图片URL--------待传
                viewModel.submitInspectRecord(request);
                break;
        }
    }

    private void submit() {
        request = new InspectRecordControllerRequest();
        // 外观状态
        String appearanceStatus = binding.tvOutlookAddedStateDevicedetail.getText().toString().trim();
        if ("正常".equals(appearanceStatus)) {
            request.setAppearanceStatus("y");
        } else if ("异常".equals(appearanceStatus)) {
            request.setAppearanceStatus("n");
        }
        // 设备状况
        String assetsStatus = binding.tvDeviceStateDevicedetail.getText().toString().trim();
        if ("正常".equals(assetsStatus)) {
            request.setAssetsStatus("y");
            request.setIsExist("y");
        } else if ("异常".equals(assetsStatus)) {
            request.setAssetsStatus("n");
            request.setIsExist("y");
        } else if ("不存在".equals(assetsStatus)) {
            //不存在的话  设备外观和状态设置为空
            request.setIsExist("n");
            request.setAssetsStatus("y");
            request.setAppearanceStatus("y");
        }
        // remark 备注
        String remark = binding.remark.getText().toString().trim();
        String encode = null;
        try {
            encode = URLEncoder.encode(remark, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (remark.length() > 0) {
            request.setRemarks(encode);
        }
        if (null != inspectTaskDtlVO && null != inspectTaskDtlVO.getTaskDtlId()) {
            request.setTaskDtlId(inspectTaskDtlVO.getTaskDtlId());
        }
//                if (null != inspectTaskDtlVO && null != inspectTaskDtlVO.getBillId()) {
//                    request.setBillId(inspectTaskDtlVO.getBillId());
//                }
        if (null != inspectTaskDtlVO && null != inspectTaskDtlVO.getInspectRecordDtlId()) {
            request.setId(inspectTaskDtlVO.getInspectRecordDtlId());
        }
        if (isDelete && null == imagePaths) {
            request.setNoRemarksPic("y");
            if (null != inspectTaskDtlVO && null != inspectTaskDtlVO.getPictureId()) {
                request.setPictureId(inspectTaskDtlVO.getPictureId());
            }
        }
        if (null != totalId && !"".equals(totalId)) {
            request.setTaskId(totalId);
        } else if (null != qrCode && !"".equals(qrCode)) {
            request.setQrCode(qrCode);
            request.setTaskDtlId(null);
            request.setTaskId(null);
        }
    }

    @Override
    protected void brodcast(Context context, String msg) {
        super.brodcast(context, msg);
         key = msg;
        if (isFind) {
            if (!isEdit && isSecond) {
                //已经保存 并且 重复扫描同一个设备无操作，无需保存 直接跳入下一个设备
                qrCode = key;
                isDone = false;
                isShow = false;
                taskDtlId = null;
                if(null != qrCode && !"".equals(qrCode)){
                    if( !isUUID(qrCode)){
                        return;
                    }
                }
                viewModel.selectDtl(totalId,null, key);
            } else {
                if ("正常".equals(binding.tvDeviceStateDevicedetail.getText().toString()) && "正常".equals(binding.tvOutlookAddedStateDevicedetail.getText().toString())) {
                    //默认保存
                    submit();
                    viewModel.submitInspectRecordBroad(request);
                } else {
                    //强提示去提交保存
                    mFail = CreateDialog.submitDialog(DeviceDetailActivity.this, "提醒", "该巡检详情还未保存，请保存",101,null,"确定");
//                    mFail = CreateDialog.infoDialog(DeviceDetailActivity.this, "提醒", "该巡检详情还未保存，请保存", "取消", "确定", v12 -> {
//                        if (null != mFail) {
//                            mFail.cancel();
//                        }
//                    }, v1 -> {
//                        if (null != mFail) {
//                            mFail.cancel();
//                        }
//                    });
                }
            }

        } else {
            // 巡检没找到的情况下，接着扫描
            qrCode = key;
            isDone = false;
            isShow = false;
            taskDtlId = null;
            if(null != qrCode && !"".equals(qrCode)){
                if( !isUUID(qrCode)){
                    return;
                }
            }
            viewModel.selectDtl(totalId,null, key);
        }

    }

    private class MyTextWatcher implements TextWatcher {
        private int limit;// 字符个数限制
        private EditText text;// 编辑框控件
        private Context context;// 上下文对象
        int cursor = 0;// 用来记录输入字符的时候光标的位置
        int before_length;// 用来标注输入某一内容之前的编辑框中的内容的长度

        public MyTextWatcher(EditText text, int limit,
                             Context context) {
            this.limit = limit;
            this.text = text;
            this.context = context;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            before_length = s.length();
        }

        /**
         * s 编辑框中全部的内容 、start 编辑框中光标所在的位置（从0开始计算）、count 从手机的输入法中输入的字符个数
         */
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            cursor = start;
        }

        @Override
        public void afterTextChanged(Editable s) {
            // 这里可以知道你已经输入的字数，大家可以自己根据需求来自定义文本控件实时的显示已经输入的字符个数
            int after_length = s.length();// 输入内容后编辑框所有内容的总长度
            // 如果字符添加后超过了限制的长度，那么就移除后面添加的那一部分，这个很关键
            binding.tvLimit.setText("(" + after_length + "/25)");
            if (after_length > limit) {
                // 比限制的最大数超出了多少字
                int d_value = after_length - limit;
                // 这时候从手机输入的字的个数
                int d_num = after_length - before_length;
                int st = cursor + (d_num - d_value);// 需要删除的超出部分的开始位置
                int en = cursor + d_num;// 需要删除的超出部分的末尾位置
                // 调用delete()方法将编辑框中超出部分的内容去掉
                Editable s_new = s.delete(st, en);
                // 给编辑框重新设置文本
                text.setText(s_new.toString());
                // 设置光标最后显示的位置为超出部分的开始位置，优化体验
                text.setSelection(st);
                // 弹出信息提示已超出字数限制
                ToastUtil.toastWarning(context, "已超出最大字数限制", -1);
            }
            if (null != inspectTaskDtlVO ) {
                if(null == inspectTaskDtlVO.getRemarks() && text.getText().length() != 0){
                    isEdit = true;
                }
                if (null != inspectTaskDtlVO.getRemarks() && !inspectTaskDtlVO.getRemarks().equals(text.getText().toString())) {
                    isEdit = true;
                }
            }

        }

    }
}
